package com.ecarx.module_network.controller;

import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.Log;


import java.util.Timer;
import java.util.TimerTask;

public class TcpPortController {

    private static final String TAG = "TcpPortController";

    private Timer timer = null;//计时器

    //adb tcpip 即可生效，setprop无效，优先级1
    private static final String TCP_PORT_1 = "service.adb.tcp.port";
    //setprop重启生效，优先级2
    private static final String TCP_PORT_2 = "persist.adb.tcp.port";
    //默认端口
    private static final String TCP_DEF_PORT = "5555";

    private String cachePort = "";

    public String getTcpPort() {
        String port = SystemProperties.get(TCP_PORT_1, "");
        if (TextUtils.isEmpty(port)) {
            port = SystemProperties.get(TCP_PORT_2, "");
            if (TextUtils.isEmpty(port)) {
                port = TCP_DEF_PORT;
            }
        }
        return port;
    }

    public void start(TcpPortChangeCallback tcpPortChangeCallback) {
        Log.d(TAG, "start: ");
        cachePort = getTcpPort();
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                String tcpPort = getTcpPort();
                if (!cachePort.equals(tcpPort)) {
                    tcpPortChangeCallback.onTcpPortChanged(tcpPort);
                    cachePort = tcpPort;
                }
            }
        };
        //2秒后执行第一次，后每隔2秒执行一次
        timer.schedule(task, 2000,2000);
    }

    //关闭
    public void stop() {
        Log.d(TAG, "stop: ");
        if (timer != null){
            timer.cancel();
            timer = null;
        }
    }

    public interface TcpPortChangeCallback {

        void onTcpPortChanged(String port);
    }
}
